<script>
export default {
  name: "Password",
  data() {
    const confirmPwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请确认密码'))
      } else if(value !== this.user.newPassword){
        callback(new Error('二次输入密码不一致'))
      }else{
        callback()
      }
    };
    return {
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'),
      rules: {
        newPassword: [
          {required: true, message: '请输入新密码', trigger: 'blur'},
          {min: 6, max: 15, message: '密码长度不能小于6位大于15位', trigger: 'blur'}
        ],
        confirmPassword: [
          {validator: confirmPwd, trigger: 'blur'}
        ]
      }
    }
  },
  created() {

  },
  methods: {
    update() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.user.password = this.user.newPassword
          this.$request.put("/user/update", this.user).then(res => {
            if (res.code === '200') {
              this.$message.success('修改密码成功，请重新登录')
              localStorage.removeItem('honey-user')
              this.$router.push('/login')
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    }
  }
}
</script>

<template>
  <div style="display: flex; align-items: center;justify-content: center;">
    <el-card style="width: 50%">
      <el-form ref="formRef" :model="user" label-width="80px" style="padding-right: 30px" :rules="rules">
        <div style="margin: 15px; text-align: center">
          <el-form-item label="原始密码" prop="password">
            <el-input v-model="user.password" disabled class="pwd_font"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="user.newPassword" show-password placeholder="请输入新密码" class="pwd_font"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="user.confirmPassword" show-password placeholder="请再次输入新密码" class="pwd_font"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div style="text-align: center">
        <el-button type="primary" plain @click="update" style="width: 80px; height: 50px;font-size: 18px">确认
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<style>

.pwd_font {
  font-size: 15px;
}
</style>